package io.github.lee.jel.ui.item.play

import android.app.Application
import android.net.Uri
import android.os.Handler
import android.os.Looper
import android.os.Message
import android.util.Log
import android.widget.SeekBar
import androidx.core.net.toUri
import androidx.databinding.ObservableField
import androidx.databinding.ObservableInt
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.MutableLiveData
import androidx.media3.common.MediaItem
import androidx.media3.common.MimeTypes
import androidx.media3.common.Player
import androidx.media3.datasource.DataSource
import androidx.media3.datasource.DefaultHttpDataSource
import androidx.media3.exoplayer.ExoPlayer
import androidx.media3.exoplayer.hls.DefaultHlsDataSourceFactory
import androidx.media3.exoplayer.hls.HlsMediaSource
import dagger.hilt.android.lifecycle.HiltViewModel
import io.github.lee.core.vm.BaseViewModel
import io.github.lee.jel.domain.Item
import io.github.lee.jel.domain.MediaSource
import javax.inject.Inject
import kotlin.math.roundToInt
import kotlin.math.roundToLong
import kotlin.time.Duration

private fun timeFormat(time: Long): String {
    val seconds = time / 1000
    val hour = seconds / 3600
    val minute = (seconds % 3600) / 60
    val second = seconds % 60
    return "%02d:%02d:%02d".format(hour, minute, second)
}

fun main() {

    println("total = ${timeFormat(5165000)}")
    println("position = ${timeFormat(1099523000000 / 10000000)}")
    println("format   = ${627812515840.toFloat().times(84)}")
    println("format   = ${(10995230000 * 1.0 / 62781251584) * 100}")


//    item?.runTimeTicks?.toFloat()?.times(84)
}//1:26:05 = 1000*5 +(1000*60*26)+(1000*60*60)

@HiltViewModel
class MediaPlayVM @Inject constructor(application: Application) : BaseViewModel(application) {

    var item: Item? = null

    private var hasPlay = false
    var player: ExoPlayer? = null
    private var currentPosition = 0L
    private fun timeFormat(time: Long): String {
        val seconds = time / 1000
        val hour = seconds / 3600
        val minute = (seconds % 3600) / 60
        val second = seconds % 60
        return "%02d:%02d:%02d".format(hour, minute, second)
    }

    val progressHandle: Handler = object : Handler(Looper.getMainLooper()) {
        override fun handleMessage(msg: Message) {
            super.handleMessage(msg)
            if (player?.playbackState == Player.STATE_READY && player?.isPlaying == true) {
                val current = player?.currentPosition ?: 0
                //播放时长
                playedTime.set(timeFormat(current))
                //进度

                val s = item?.runTimeTicks.toString()
                val totalMinute = if (s.length == 11) {
                    (item?.runTimeTicks ?: 0) / 10
                } else {
                    item?.runTimeTicks ?: 0
                }
                val total = totalMinute / 1000L
                val p = ((current * 1.0 / total) * 100).roundToInt()
                Log.e("TAG", "current = $current,total = $total, progress = $p")
                progress.set(p)
                //总时长
                totalTime.set(timeFormat(total))

                sendEmptyMessageDelayed(1, 500)

            }
        }

    }
    private val listener = PlayListener(this)
    val closeClickLiveData = MutableLiveData(false)
    val isPlayingLiveData = MutableLiveData(false)
    val playedTime = ObservableField("00:00:00")
    val progress = ObservableInt(0)
    val totalTime = ObservableField("00:00:00")


    override fun onResume(owner: LifecycleOwner) {
        super.onResume(owner)
        if (hasPlay) {
            player?.play()
        }
    }

    override fun onStop(owner: LifecycleOwner) {
        super.onStop(owner)
        currentPosition = player?.currentPosition ?: 0
        player?.pause()
    }

    override fun onDestroy(owner: LifecycleOwner) {
        super.onDestroy(owner)
        progressHandle.removeCallbacksAndMessages(null)
        player?.removeListener(listener)
        player?.stop()
        player?.release()
    }

    fun setUri(uri: Uri): ExoPlayer? {

        player = ExoPlayer.Builder(mContext)
            .build()
        val mediaItem = MediaItem.Builder()
            .setUri(uri)
//            .setMimeType(MimeTypes.APPLICATION_M3U8)
            .build()
//        val mediaItem = MediaItem.fromUri(uri)
        player?.setMediaItem(mediaItem)
        player?.addListener(listener)
//        val dataSourceFactory: DataSource.Factory = DefaultHttpDataSource.Factory()
//        val a =HlsMediaSource.Factory(dataSourceFactory).createMediaSource(mediaItem)
//
//
//        player?.setMediaSource()
        return player
    }

    fun startPlay() {

        Log.e("TAG","player?.isCurrentMediaItemSeekable = ${player?.isCurrentMediaItemSeekable}")

//        isCurrentWindowSeekable
        player?.prepare()
        player?.playWhenReady = true
        hasPlay = true
    }

    fun close() {
        closeClickLiveData.postValue(true)
    }

    /**切换播放暂停*/
    fun togglePlay() {
        if (player?.isPlaying == true) {
            player?.pause()
        } else {
            player?.play()
        }
        isPlayingLiveData.postValue(player?.isPlaying ?: false)
    }

    fun onStartTrackingTouch() {
        player?.pause()
        Log.e("TAG", "player?.duration = ${player?.duration}")

    }
    fun onStopTrackingTouch(seekBar: SeekBar) {
        val total = item?.runTimeTicksMillisecond() ?: 0

        val current = (total * 1.0F * (seekBar.progress / 100F)).roundToLong()
        Log.e("TAG", "current = $current")
        player?.seekTo(current)
        player?.playWhenReady=true
//        player?.play()
    }
}